package com.baidu.iit.pxp.listener;

import com.baidu.iit.pvm.ActivityIllegalArgumentException;
import com.baidu.iit.pxp.delegate.Expression;
import com.baidu.iit.pxp.el.NoExecutionVariableScope;
import com.baidu.iit.pxp.event.ActivityEvent;

/**
 * User: huangweili
 * Date: 14-4-30
 * Time: 下午4:05
 */
public class DelegateExpressionActivitiEventListener extends BaseDelegateEventListener {

    protected Expression expression;
    protected boolean failOnException = true;

    public DelegateExpressionActivitiEventListener(Expression expression, Class<?> entityClass) {
        this.expression = expression;
        setEntityClass(entityClass);
    }

    @Override
    public void onEvent(ActivityEvent event) {
        if(isValidEvent(event)) {
            NoExecutionVariableScope scope = new NoExecutionVariableScope();

            Object delegate = expression.getValue(scope);
            if (delegate instanceof ActivityEventListener) {
                 failOnException = ((ActivityEventListener) delegate).isFailOnException();

                ((ActivityEventListener) delegate).onEvent(event);
            } else {

                failOnException = true;
                throw new ActivityIllegalArgumentException("Delegate expression " + expression
                        + " did not resolve to an implementation of " + ActivityEventListener.class.getName());
            }
        }
    }

    @Override
    public boolean isFailOnException() {
        return failOnException;
    }

}
